package top.superxuqc.sendmsg.util;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Base64;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;


import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import top.superxuqc.sendmsg.util.domain.MSG;

public class SendHttp {



    public static void send(Handler handler){
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        String format = sf.format(date);
        String timestamp = String.valueOf(date.getTime() / 1000);
        //Base64.encode()
        MSG m = new MSG("20182*****","name","计算机科学与技术学院","2018","openid","重庆市,重庆市,南岸区","吃饭","门口",
                format,"市内当日离返校",format,"",timestamp);
        String data = m.toString();

        byte[] encodeData = Base64.encode(data.getBytes(), Base64.DEFAULT);
        String s = new String(encodeData);
        sendPost("https://we.cqupt.edu.cn/api/lxsp/post_lxsp_spxx_test0914.php", s,handler);



    }


    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url
     *            发送请求的 URL
     * @param param
     *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static void sendPost(String url, String param,Handler handler) {
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody requestBody = new FormBody.Builder()
                .add("key", param)
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        //异步请求
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {

                String result = response.body().string();

                Message msg = new Message();
                Bundle bundle = new Bundle();
                bundle.putString("result",result);
                msg.setData(bundle);
                handler.sendMessage(msg);
                System.out.println(result);
            }
        });
    }

}
